<!--
  绘制流程图右侧 属性栏
-->

<template>
  <div ref="bpmnPanel" class="property-panel">
    <Collapse simple v-model="collapseValue">
      <Panel name="1">
        基本设置
        <Form ref="formInline" slot="content" :label-width="50" :model="form">
          <FormItem label="key">
            <Input type="text" v-model="form.id" placeholder="key" @input="updateKey"></Input>
          </FormItem>
          <FormItem label="名称">
            <Input v-model="form.name" placeholder="名称" @input="updateName"></Input>
          </FormItem>
          <!--          <div  v-if="rootElement">-->
          <!--            <FormItem label="版本号">-->
          <!--              <Input v-model="form.versionTag" @input="updateProperties({versionTag: form.versionTag || undefined})" ></Input>-->
          <!--            </FormItem>-->
          <!--            <FormItem label="任务级别">-->
          <!--              <Input v-model="form.taskPriority" @input="updateProperties({taskPriority: form.taskPriority || undefined})"></Input>-->
          <!--            </FormItem>-->
          <!--            <FormItem label="工作级别">-->
          <!--              <Input v-model="form.jobPriority" @input="updateProperties({jobPriority: form.jobPriority || undefined})"></Input>-->
          <!--            </FormItem>-->
          <!--            <FormItem label="保留时间">-->
          <!--              <Input v-model="form.historyTimeToLive" @input="updateProperties({historyTimeToLive: form.historyTimeToLive || undefined})"></Input>-->
          <!--            </FormItem>-->
          <!--          </div>-->
        </Form>
      </Panel>
      <Panel name="2" v-if="isUserTask">
        审核者
        <Form ref="userTaskForm" slot="content" :label-width="50" :model="userTask">
          <FormItem label="类型">
            <RadioGroup v-model="choiseType" type="button">
              <Radio label="single">单人</Radio>
              <Radio label="plural">多人</Radio>
              <Radio label="role">角色</Radio>
            </RadioGroup>
          </FormItem>
          <FormItem label="单人" v-if="choiseType==='single'">
            <Input v-model="userTask.assigneeName" clearable readonly placeholder="请选择处理人">
              <span slot="append" class="add-pointer"><Icon type="md-add" @click="choiseProcessor"/></span>
            </Input>
          </FormItem>
          <FormItem label="多人" v-if="choiseType==='plural'">
            <Input v-model="userTask.candidateUsersName" clearable readonly placeholder="请选择处理人">
              <span slot="append" class="add-pointer"><Icon type="md-add" @click="choiseProcessor"/></span>
            </Input>
          </FormItem>
          <FormItem label="角色" v-if="choiseType==='role'">
            <Input v-model="userTask.candidateGroupsName" clearable readonly placeholder="请选择角色">
              <span slot="append" class="add-pointer"><Icon type="md-add" @click="choiseRoles"/></span>
            </Input>
          </FormItem>
        </Form>
      </Panel>
      <Panel name="3" v-if="isExclusiveSequenceFlow">
        流转条件
        <Input v-model="exclusiveSequence.conditionExpression" slot="content" clearable placeholder="例如：${leaveDays>2}"
               @input="updateConditionExpression"></Input>
      </Panel>
    </Collapse>
    <Modal
      v-model="modal.show"
      :title="modal.title"
      :width="modal.width"
      @on-cancel="closeModal"
      scrollable
      class="modal-area"
      footer-hide
    >
      <check-user v-if="modal.type==='user'" :isSingle="choiseType==='single'" :checkedArr="checkedArr"
                  @close-modal="closeModal"
                  @sure-back="checkedUser"></check-user>
      <check-role v-if="modal.type==='role'" :isSingle="false" @close-modal="closeModal" :checkedArr="checkedArr"
                  @sure-back="checkedRole"></check-role>
    </Modal>
  </div>
</template>

<script>
import elementHelper from 'bpmn-js-properties-panel/lib/helper/ElementHelper'
import CmdHelper from 'bpmn-js-properties-panel/lib/helper/CmdHelper'
import checkUser from '_c/sys-components/check-user'
import checkRole from "_c/sys-components/check-role"
import {mapState} from "vuex";


export default {
  name: "bpmn-panel",
  props: {
    modeler: {
      type: Object,
      required: true
    }
  },
  components: {checkUser, checkRole},
  data() {
    return {
      xmlUtil: null,
      choiseType: "single",//选择审核人的类型
      modal: {
        show: false,
        title: "",
        type: "",
        width: 300,
      },
      checkedArr: [],
      collapseValue: "1",
      element: {},
      rootElement: null,
      activeName: '1',
      form: {
        id: '',
        name: '',
        versionTag: '',
        taskPriority: '',
        jobPriority: '',
        candidateStarterGroups: '',
        candidateStarterUsersNames: '',
        candidateStarterUsers: '',
        historyTimeToLive: '',
        // 流程发起人
        initiator: '',
        description: ''
      },
      userTask: {
        assigneeType: '1',
        assigneeName: '',
        assignee: '',
        candidateUsersName: '',
        candidateUsers: '',
        candidateGroups: '',
        candidateGroupsName: '',
        // roleIds: '',
        // roleNames: '',
      },
      exclusiveSequence: {
        conditionExpression: ''
      },
    }
  },
  computed: {
    ...mapState({
        redis: state => state.user.redis   //使用ES6的箭头函数来给count赋值
      }
    ),

    isEvent() {
      if (!this.element) {
        return
      }
      return this.verifyIsEvent(this.element.type)
    },
    //是否是人员审核任务
    isUserTask() {
      if (this.element && this.element.type === 'bpmn:UserTask') {
        const {businessObject} = this.element
        if (businessObject.name) {
          this.collapseValue = "2"
        } else {
          this.collapseValue = "1"
        }
        return true;
      } else {
        this.collapseValue = "1"
        return false;
      }
    },
    //是否为开始节点
    isStart() {
      if (!this.element) {
        return
      }
      return this.verifyIsStart(this.element.type)
    },
    //是否为执行路线
    isExclusiveSequenceFlow() {
      if (!this.element) {
        return
      }
      const {businessObject} = this.element
      if (businessObject && businessObject.sourceRef && businessObject.sourceRef.$type === 'bpmn:ExclusiveGateway') {
        if (businessObject.name) {
          this.collapseValue = "3"
        } else {
          this.collapseValue = "1"
        }
        return true
      }
      return false
    },
  },
  created() {
    this.init()
  },
  methods: {
    //选择审核人，打开弹窗
    choiseProcessor() {
      this.modal.show = true
      this.modal.width = 500
      this.modal.type = "user"
      this.modal.title = "选择审核人"
    },

    choiseRoles() {
      this.modal.show = true
      this.modal.width = 500
      this.modal.type = "role"
      this.modal.title = "选择角色"
    },
    checkedRole(arr) {
      this.userTask.candidateGroupsName = arr.map(m => m.roleName).join(',')
      this.userTask.candidateGroups = arr.map(m => m.id).join(',')
      this.userTask.assignee = ""
      this.userTask.assigneeName = ""
      this.userTask.candidateUsers = ""
      this.userTask.candidateUsersName = ""
      let updateMap = {candidateGroups: this.userTask.candidateGroups, candidateUsers: "", assignee: ""};
      this.updateProperties(updateMap)
      this.closeModal()
    },

    //获取勾选的人员
    checkedUser(obj) {
      let updateMap = {}
      switch (this.choiseType) {
        //单选
        case "single":
          this.userTask.assignee = obj.id
          this.userTask.assigneeName = obj.name
          this.userTask.candidateUsers = ""
          this.userTask.candidateUsersName = ""
          this.userTask.candidateGroups = ""
          this.userTask.candidateGroupsName = ""
          updateMap = {assignee: this.userTask.assignee, candidateUsers: "", candidateGroups: ""};
          break;
        //多选
        case "plural":
          this.userTask.assignee = ""
          this.userTask.assigneeName = ""
          this.userTask.candidateGroups = ""
          this.userTask.candidateGroupsName = ""
          this.userTask.candidateUsers = obj.map(m => m.id).join(',')
          this.userTask.candidateUsersName = obj.map(m => m.name).join(',')
          updateMap = {candidateUsers: this.userTask.candidateUsers, assignee: "", candidateGroups: ""};
          break;
        default:
          break;
      }
      //更新属性
      this.updateProperties(updateMap)
      this.closeModal()
    },

    closeModal() {
      let cleanModal = {
        show: false,
        title: "",
        type: "",
        width: 300
      }
      this.modal = Object.assign({}, cleanModal)
    },

    //初始化
    init() {
      const that = this
      this.modeler.on('selection.changed', e => {
        that.element = e.newSelection[0]
        that.rootElement = null
        that.setDefaultProperties(that.element)
      })
      this.modeler.on('element.changed', e => {
        const {element} = e
        const {element: currentElement} = this
        if (!currentElement) {
          return
        }
        // update panel, if currently selected element changed
        if (element.id === currentElement.id) {
          this.element = element
        }
      })
      this.modeler.on('element.click', e => {
        if (!that.element) {
          that.rootElement = e.element
          that.setDefaultProperties(that.rootElement)
        }
      })
      this.modeler.on('root.added', function (e) {
        if (!that.element) {
          that.rootElement = e.element
          that.setDefaultProperties(that.rootElement)
        }
      })
    },
    setDefaultProperties(element) {
      if (element) {
        const {businessObject} = element
        let userCopy = {
          assigneeType: '1',
          assigneeName: '',
          assignee: '',
          candidateUsersName: '',
          candidateUsers: '',
          candidateGroups: '',
          candidateGroupsName: ''
        }
        this.userTask = businessObject ? businessObject : userCopy
        if (this.userTask.candidateGroups) {
          this.choiseType = 'role'
        } else if (this.userTask.candidateUsers) {
          this.choiseType = 'plural'
        } else if (this.userTask.assignee) {
          this.choiseType = 'single'
        }
        const candidateStarterUsersNames = this.form.candidateStarterUsersNames
        this.form = {
          ...businessObject,
          ...businessObject.$attrs
        }
        this.form.candidateStarterUsersNames = candidateStarterUsersNames
        if (element.type === 'bpmn:Process') {
          this.setProcessUser()
        } else if (this.isUserTask) {
          this.setUserTaskUser()
        }
      }
    },
    setProcessUser() {
      let userIds = []
      if (this.form.candidateStarterUsers) {
        userIds = this.form.candidateStarterUsers.split(',')
      }
      if (userIds.length === 0) {
        return
      }
    },
    setUserTaskUser() {
      const userIds = []
      switch (this.choiseType) {
        case "single":
          this.checkedArr = this.userTask.assignee ? this.userTask.assignee.split(',').map(m => {
            return {id: m, name: this.redis.userMap[m]}
          }) : []
          break;
        case "plural":
          this.checkedArr = this.userTask.candidateUsers ? this.userTask.candidateUsers.split(',').map(m => {
            return {id: m, name: this.redis.userMap[m]}
          }) : []
          break;
        case "role":
          this.checkedArr = this.userTask.candidateGroups ? this.userTask.candidateGroups.split(',').map(m => {
            return {id: m, name: this.redis.roleMap[m]}
          }) : []
          break;

      }
      if (this.userTask.assignee) {
        userIds.push(this.userTask.assignee)
      }
      if (this.userTask.candidateUsers) {
        const candidateUsers = this.userTask.candidateUsers.split(',')
        userIds.push(candidateUsers)
      }
      if (this.userTask.assignee) {
        this.userTask.assigneeName = this.redis.userMap[this.userTask.assignee]
      }
      this.userTask.candidateUsersName = this.userTask.candidateUsers ? this.userTask.candidateUsers.split(',').map(m => this.redis.userMap[m]) + "" : ""
      this.userTask.candidateGroupsName = this.userTask.candidateGroups ? this.userTask.candidateGroups.split(',').map(m => this.redis.roleMap[m]) + "" : ""
      if (userIds.length === 0) {
        return
      }
    },
    verifyIsEvent(type) {
      if (!type) return
      return type.includes('Event')
    },
    verifyIsStart(type) {
      return type === 'bpmn:StartEvent'
    },
    updateName(name) {
      this.updateProperties({name: name})
    },
    updateKey(key) {
      this.updateProperties({id: key})
    },

    //更新元素属性
    updateProperties(properties) {
      const modeling = this.modeler.get('modeling')
      modeling.updateProperties(this.element ? this.element : this.rootElement, properties)
    },

    // 条件分支设置
    updateConditionExpression() {
      if (!this.element) return
      const {businessObject} = this.element
      const bpmnFactory = this.modeler.get('bpmnFactory')
      const conditionOrConditionExpression = elementHelper.createElement(
        'bpmn:FormalExpression',
        {
          body: this.exclusiveSequence.conditionExpression
        },
        businessObject,
        bpmnFactory
      )

      const command = CmdHelper.updateBusinessObject(this.element, businessObject, {
        conditionExpression: conditionOrConditionExpression
      })

      this.executeCommand(command)
    },
    executeCommand(command) {
      const commandStack = this.modeler.get('commandStack')
      commandStack.execute(command.cmd, command.context)
    },
  }
}
</script>

<style lang="less" scoped>
.property-panel {
  width: 398px;

}
</style>
